import { translateDotSeparatedName } from '@amcax/base';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { docMgr, userEvents } from '@app-cad/module';
import { Tooltip } from 'antd';
import { FC, MouseEvent, useMemo } from 'react';
import { CADIcons } from '../../../LeftPanel';
import { RelationsEvents } from './types';

interface ObjectItemProps {
  dxid: string;
  selectedDxids: string[];
  onSelect: (dxid: string, event: MouseEvent<HTMLSpanElement>) => void;
}

export const RelationObjectItem: FC<ObjectItemProps> = ({
  dxid,
  selectedDxids,
  onSelect,
}) => {
  const documentObject = useMemo(
    () => docMgr.getDocumentObjectById(dxid),
    [dxid],
  );

  const selected = selectedDxids.includes(dxid);

  const handleClick = (event: MouseEvent<HTMLSpanElement>) => {
    onSelect(dxid, event);
  };

  function handleContextMenu(event: MouseEvent<HTMLSpanElement>) {
    userEvents.emit(RelationsEvents.ShowMenu, {
      documentObject,
      selectedDxids,
      event,
    });
  }

  if (!documentObject) {
    return (
      <Tooltip
        title='数据错误，该对象可能已删除'
        placement='right'
        color='white'
        overlayInnerStyle={{ color: 'black' }}
      >
        <QuestionCircleOutlined style={{ marginLeft: '.5rem' }} />
      </Tooltip>
    );
  }

  return (
    <span
      className={`inline-flex align-middle gap-1 cursor-pointer hover:bg-[#c1c0ee] px-2 rounded-md select-none ${selected ? 'bg-[#4e4ede] text-white' : ''}`}
      onClick={handleClick}
      onContextMenu={handleContextMenu}
    >
      <CADIcons
        data={{
          ...documentObject,
          originalObj: documentObject,
        }}
      />
      <span>{translateDotSeparatedName(documentObject.label)}</span>
    </span>
  );
};
